<template>
<!-- 筛选区 -->
   <div class="sub-filter">
     <div class="item" v-for="item in list" :key="item.id">
       <div class="head">{{item.name}}：</div>
       <div class="body">
         <a href="javascript:;" :class="{active:item.activeName===undefined}" @click="getAttrFn(item,{})">全部</a>
         <a href="javascript:;" :class="{active:item.activeName===i.name}" v-for="i in item.properties" :key="i.name" @click="getAttrFn(item,i)">{{i.name}}</a>
       </div>
     </div>
   </div>
</template>

<script>
import { computed, inject, reactive, toRef, watch } from 'vue'
import { useRoute } from 'vue-router'

export default {
  name: 'SubFilter',
  setup () {
    const route = useRoute()
    const subCate = inject('subCate')
    const sortParams = inject('sortParams')
    console.log(subCate.value)
    // const list = ref([
    //   { id: null, name: '品牌', properties: subCate.value.brands },
    //   ...subCate.value.saleProperties
    // ])
    // 品牌数据处理成响应式的  class才会变 否则视图更新不同步
    const brands = reactive({ id: null, name: '品牌', properties: subCate.value.brands })
    console.log(brands)
    const list = computed(() => {
      // 🔔计算属性内的 subCate 是依赖项，依赖项数据发生变化，computed 会重新计算得到新结果
      return [
        brands,
        ...subCate.value.saleProperties
      ]
    })
    // 处理品牌选择其他id不会回到全部
    watch(() => route.params.id, () => {
      //  brands = reactive({ id: null, name: '品牌', properties: subCate.value.brands })
      brands.activeName = undefined
    })
    const attrs = toRef(sortParams, 'attrs')
    const brandId = toRef(sortParams, 'brandId')
    const getAttrFn = (theItem, theProp) => {
      console.log(attrs)
      // 点击属性名称，并通过：class绑定高亮
      theItem.activeName = theProp.name
      // 🔔 点击品牌的时候，收集的是品牌的id，并且需要存储到一个叫 brandId 的字段中
      if (theItem.name === '品牌') {
        brandId.value = theProp.id
        return
      }
      // 点击的时候有2中情况
      const index = attrs.value.findIndex(item => item.groupName === theItem.name)
      // 情况1：当前属性没有被点击过，就添加一份新的属性数据
      if (index === -1) {
        attrs.value.push({ groupName: theItem.name, propertyName: theItem.activeName })
      } else {
        // 情况2：已经有属性字段了，就修改值即可
        attrs.value[index].propertyName = theItem.activeName
      }
      // 取消一些无效的值
      attrs.value = attrs.value.filter(item => item.propertyName)
    }

    // console.log(list)
    return { list, getAttrFn }
  }
}
</script>

<style scoped lang='less'>
  // 筛选区
  .sub-filter {
    background: #fff;
    padding: 25px;
    .item {
      display: flex;
      line-height: 40px;
      .head {
        width: 80px;
        color: #999;
      }
      .body {
        flex: 1;
        a {
          margin-right: 36px;
          transition: all .3s;
          display: inline-block;
          &.active,
          &:hover {
            color: @xtxColor;
          }
        }
      }
    }
  }
</style>
